<script setup lang="ts">
import { onMounted } from "vue";
import { useBooksStore } from "../stores/books";
import { useRouter } from "vue-router";

const books = useBooksStore();
const router = useRouter();

onMounted(() => {
  books.loadBooks();
});

function onImport(e: Event) {
  const input = e.target as HTMLInputElement;
  if (input.files && input.files.length) {
    books.importFiles(input.files);
    input.value = "";
  }
}

function open(bookId: string) {
  router.push({ name: "reader", params: { bookId } });
}
</script>

<template>
  <div class="page">
    <div class="toolbar">
      <label class="import-btn">
        导入TXT
        <input type="file" accept=".txt,text/plain" multiple @change="onImport">
      </label>
    </div>

    <ul class="book-list">
      <li v-for="b in books.books" :key="b.id" class="book-item" @click="open(b.id)">
        <div class="cover">📘</div>
        <div class="meta">
          <div class="title">{{ b.title }}</div>
          <div class="sub">{{ (b.size / 1024).toFixed(1) }} KB · {{ new Date(b.updatedAt).toLocaleString() }}</div>
        </div>
      </li>
      <li v-if="!books.books.length" class="empty">尚未导入书籍，点击上方“导入TXT”。</li>
    </ul>
  </div>
</template>

<style scoped>
.page { padding: 12px; }
.toolbar { display: flex; justify-content: flex-end; margin-bottom: 8px; }
.import-btn { position: relative; display: inline-block; padding: 8px 12px; border: 1px solid #ddd; border-radius: 6px; background: #fff; color: #333; }
.import-btn input { position: absolute; inset: 0; opacity: 0; width: 100%; height: 100%; }
.book-list { list-style: none; margin: 0; padding: 0; }
.book-item { display: flex; gap: 12px; padding: 10px; background: #fff; border-radius: 8px; margin-bottom: 8px; align-items: center; }
.cover { width: 40px; height: 56px; background: #e6f4ff; border: 1px solid #cde6ff; display: flex; align-items: center; justify-content: center; border-radius: 4px; font-size: 18px; }
.meta { flex: 1; }
.title { font-weight: 600; }
.sub { font-size: 12px; color: #666; }
.empty { text-align: center; color: #888; padding: 20px 0; }
</style>
